import uicls
import uiutil
import uiconst
import blue
import math
import log

class OldTransform(uicls._BaseDecoCore, uicls._GetDecoMetaclassInst('triui.UITransform')):
    __guid__ = 'uicls.OldTransform'
    default_name = 'transform'
    default_state = uiconst.UI_PICKCHILDREN
    default_rotation = 0.0
    default_clipChildren = False
    default_pickRadius = 0
    default_opacity = 1.0

    def ApplyAttributes(self, attributes):
        uicls._BaseDecoCore.ApplyAttributes(self, attributes)
        self._rotation = 0.0
        self.opacity = attributes.get('opacity', self.default_opacity)
        for attrName in ('clipChildren', 'pickRadius'):
            attr = attributes.get(attrName, getattr(self, ('default_' + attrName)))
            if (attr is not None):
                setattr(self, attrName, attr)

        self.SetRotation(attributes.get('rotation', self.default_rotation))



    def SetRotation(self, rotation = 0):
        self.transform.RotationZ(rotation)
        self._rotation = rotation



    def Rotate(self, delta):
        newRotation = self.ClampRotation((self._rotation + delta))
        self.SetRotation(newRotation)



    def GetRotation(self):
        return self._rotation



    def ClampRotation(self, rotation):
        if (rotation > (math.pi * 2)):
            rotation -= (math.pi * 2)
        elif (rotation < 0):
            rotation += (math.pi * 2)
        return rotation



    def StartRotationCycle(self, direction = 1, cycleTime = 1000.0, cycles = None):
        if getattr(self, '_rotateCycle', False):
            self._rotateCycle = False
            blue.pyos.synchro.Yield()
        self._rotateCycle = True
        fullRotation = (math.pi * 2)
        start = blue.os.GetTime()
        ndt = 0.0
        current = self.GetRotation()
        cycleCount = 0
        while getattr(self, '_rotateCycle', False):
            try:
                ndt = max(ndt, (blue.os.TimeDiffInMs(start) / cycleTime))
            except:
                log.LogWarn(('StartRotationCycle::Failed getting time diff. Diff should not exceed %s but is %s' % (cycleTime, (start - blue.os.GetTime(1)))))
                ndt = 1.0
            self.SetRotation((current - ((fullRotation * ndt) * direction)))
            blue.pyos.synchro.Yield()
            if self.destroyed:
                return 
            if ((cycles is not None) and (cycles <= int(ndt))):
                return 




    def StopRotationCycle(self):
        self._rotateCycle = False



    def Flush(self):
        for child in self.children[:]:
            if ((child is not None) and (not getattr(child, 'destroyed', 0))):
                child.Close()

        del self.children[:]



    def SetOpacity(self, opacity):
        self.opacity = opacity




class Transform(OldTransform):
    __guid__ = 'uicls.Transform'


